<meta charset="utf-8">

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class upload extends CI_Controller {

	private $all_session;
	private $mem_type;
	private $data;
	private $mem_id;

	public function __construct()
    {
        parent::__construct();

        @$this->all_session = $this->session->all_userdata();  
        @$this->mem_type = $this->all_session['login'][0]['mem_type'];   
        $this->mem_id = $this->all_session['login'][0]['mem_id'];

        if($this->mem_type != 2 && $this->mem_type != 1)
        {
        	redirect('authen');
        } 
    }

    
	public function index()
	{
		$this->load->view('upload_form', array('error' => ' ' ));
	}

	public function upload_vdo()
	{
		$all_session = $this->session->all_userdata();
		$mem_id = $all_session['login'][0]['mem_id'];
		$server_id = $this->input->post('select_server');

		$data['server'] = $this->upload_model->get_server($server_id);


		$vdo_uniq = uniqid();

		//if($_POST[Submit]){
		//set limit timeout 
		set_time_limit(3000);
		//set up basic connection
		@$ftp_server = $data['server'][0]['server_ip'];
		@$ftp_user_name = $data['server'][0]['ftp_name'];
		@$ftp_user_pass = base64_decode($data['server'][0]['ftp_pass']);		

		// destinationfile
		@$destination_file = $vdo_uniq.'_'.$_FILES['file']['name'];
		$destination_file = str_replace(" ", "", $destination_file);

		// detailfile
		@$source_file = $_FILES['file']['tmp_name'];
		@$size_file = $_FILES['file']['size'];
		$conn_id = ftp_connect($ftp_server);
	 
		// login with username and password
		@$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass); 

		@ftp_chdir(@$conn_id,"");
		// check connection  
	 	if ((!$conn_id) || (!$login_result)) {
	 		redirect('pvdo/upload/error');
	    	exit;
	 	} else {
	    	//echo "Connected to $ftp_server, for user $ftp_user_name<br/>";     
	 	}      
		
		// upload the file  
		$upload = ftp_put($conn_id, $destination_file, $source_file, FTP_BINARY);    

		// check upload status  
	 	if (!$upload) {
	     echo "FTP upload has failed!";
	     $all_session = $this->session->all_userdata();
		
			$log_file = array(						
				'log_url' => base_url().'index.php/pvdo/upload',
				'log_action' => 'Upload Vdo',
				'log_target' => $destination_file,
				'log_status' => 'Fail',
				'mem_id' => $all_session['login'][0]['mem_id'],
				'log_ip' => $_SERVER['REMOTE_ADDR']						
			);
			$this->logfile_model->add_logfile($log_file);
			redirect('pvdo/upload/error');
	  	} else {
	  		// redirect to convert.php (stream server) and $_POST['$destination_file'] when upload complete
			//header("Location: http://10.176.200.200/server/convert/index.php?vdo_name=$destination_file");
	  		
	  	}

		// close the FTP stream  
		ftp_close($conn_id);//}//end $_POST[Submit]


		//////////////////////////////////////
		/////////// Create Thumb  ////////////
		//////////////////////////////////////


		$videofile = $_FILES['file']['tmp_name'];
		$videofile = str_replace(" ", "", $videofile);
		$videofile = iconv("utf-8","tis-620",$videofile);


		ob_start();
		passthru("C:/ffmpeg/bin/ffmpeg.exe -i \"{$videofile}\" 2>&1");
		$duration = ob_get_contents();
		ob_end_clean();

		$search='/Duration: (.*?),/';
		$duration=preg_match($search, $duration, $matches, PREG_OFFSET_CAPTURE, 3);
		//TEST ECHO 
		// echo "<pre>";
		// print_r($matches);
		$timeduration = $matches[1][0];

		$this->create_thumb($videofile,$destination_file,$timeduration);
	


		//////////////////////////////////////
		////////////////  Data  //////////////
		//////////////////////////////////////
		$vdo = array(
			'vdo_name' => $_FILES['file']['name'],
			'server_id' => $server_id,
			'mem_id' => $mem_id,
			'vdo_timeduration' => $timeduration,
			'vdo_size' => $size_file,
			'vdo_rawfile' => $destination_file,
			'vdo_uniqid' => $vdo_uniq
		);
		$this->upload_model->upload_vdo($vdo);

		$data['vdo'] = $this->upload_model->get_vdo($vdo_uniq);
		$vdo_id = $data['vdo'][0]['vdo_id'];


		for($j=1;$j<=3;$j++){
			if($j == 1)
			{
				$thumb_choose = 1 ;
			}else{
				$thumb_choose = 0 ;
			}
			$vdo_thumb = array(
				'thumb_name' => $destination_file."_".$j.".jpg",
				'vdo_id' => $vdo_id,
				'thumb_choose' => $thumb_choose
			);
			$this->upload_model->insert_thumb($vdo_thumb);
			
		};

		$id = $this->pvdo_model->redirect($destination_file);
		$id = $id[0]['vdo_id'];


		//////////////////////////////////////
		////////////////  Data  //////////////
		//////////////////////////////////////
		$all_session = $this->session->all_userdata();
		
		$log_file = array(						
			'log_url' => base_url().'index.php/pvdo/upload',
			'log_action' => 'Upload Vdo',
			'log_target' => $vdo['vdo_name'],
			'log_status' => 'Pass',
			'mem_id' => $all_session['login'][0]['mem_id'],
			'log_ip' => $_SERVER['REMOTE_ADDR']						
		);
		$this->logfile_model->add_logfile($log_file);
		
		redirect('pvdo/profile/'.$id);

	

	}

	public function create_thumb($videofile,$destination_file,$timeduration)
	{

		$vod_thumb = "vod_thumb/$destination_file";
		$vod_thumb = iconv("utf-8","tis-620",$vod_thumb);
		mkdir($vod_thumb, 0777);

		$min_time = '00:00:00';
		$max_time = $timeduration;
		

	    $min_epoch = strtotime($min_time);
	    $max_epoch = strtotime($max_time);

	   
	    
	    $destination_file = iconv("utf-8","tis-620",$destination_file);
	    $timeduration = iconv("utf-8","tis-620",$timeduration);


	    for($i=1;$i<=3;$i++)
	    {
	    	$rand_epoch = rand($min_epoch, $max_epoch);
	    	$rand_thumb = date('H:i:s', $rand_epoch);
			
			exec( "C:/ffmpeg/bin/ffmpeg.exe -i \"{$videofile}\" -vframes 1 -ss \"{$rand_thumb}\" -s 640x360 vod_thumb/$destination_file/\"{$destination_file}\"_\"{$i}\".jpg");


	    }

	}
		

}
?>